package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.PageResult;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.entity.Cate;
import com.itheima.ydd.service.CateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
@RequestMapping("/ydd_cate")
public class CateController {

    @Autowired
    private CateService cateService;


    /**
     * 分类详情
     * @param id
     * @return
     */
    @GetMapping("/rowInfo")
    public ResultData rewInfo(int id){
        Cate cate = cateService.getById(id);
        return ResultData.ok("",cate);
    }

    @GetMapping("list")
    public ResultData list(int page,int limit,String catename){
        Page<Cate> pageInfo=new Page<>(page,limit);
        LambdaQueryWrapper<Cate> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.like(catename!=null,Cate::getCatename,catename);
        long count = cateService.count();
        long pageSize=limit;
        long currentPage=page;
        List<Cate> list = cateService.list(queryWrapper);
        Page<Cate> catePage = cateService.page(pageInfo, queryWrapper);
        List<Cate> records = catePage.getRecords();
        return ResultData.ok("", PageResult.init(count,pageSize,currentPage,records));
    }


    @GetMapping("del")
    public ResultData del(int id){
        cateService.removeById(id);
        return ResultData.ok("","删除成功");
    }

    @PostMapping("update")
    public ResultData update(@RequestBody Cate cate){
        cateService.updateById(cate);
        return ResultData.ok("","修改成功");
    }

    @PostMapping("/add")
    public ResultData add(@RequestBody Cate cate){
        cateService.save1(cate);
        return ResultData.ok("","添加成功");
    }

    @GetMapping("/all")
    public ResultData all(){
        List<Cate> list = cateService.list();
        return ResultData.ok("",list);
    }
}
